<?php

namespace app\service\pixel;

use app\model\BatchUpdate;
use app\model\PixelLogs;
use app\model\FacebookPixels;
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\ServerSide\ActionSource;
use FacebookAds\Object\ServerSide\Content;
use FacebookAds\Object\ServerSide\CustomData;
use FacebookAds\Object\ServerSide\DeliveryCategory;
use FacebookAds\Object\ServerSide\Event;
use FacebookAds\Object\ServerSide\EventRequest;
use FacebookAds\Object\ServerSide\EventRequestAsync;
use FacebookAds\Object\ServerSide\UserData;
use GuzzleHttp\Promise\Utils;
use think\Collection;
use think\helper\Arr;

class FaceBookPixelTrack
{
    use FacebookTrait;
    const FB_ACCESS_TOKEN = "EAAIhLKhU8NMBOw8hmFlsnlQK8fIBztug3RgilvgdWZBdbSnIKnZAhLRszwzo7BwWOZATnhdYl4fziHZCJZBrVPhzYy1sZASBrtFeWfGBCZCjuxLLSYSaBHqsns8kSTo0qrDZAs6ppTA4sLc0NTK1wJcBcsD4pvQ7ZAbRrGCOAsmltBGYkLvTrZCZAjtFY2lZCA3xUZB5RkgZDZD";


    //根据像素复制追踪日志
    public function copyPixelTrackLogByPixelIds(PixelLogs $log)
    {
        $facebookSetList = FacebookPixels::getPixelIds();
        if (empty($facebookSetList)) return [];
        $logs = [];
        $log->pixel_id = Arr::first($facebookSetList);
        $log->save();
        foreach ($facebookSetList as $index => $pixel_id) {
            if ($index) {
                $copLog = PixelLogs::copyTrackLogs($log, $pixel_id);
                $logs[] = [
                    'pixel_id' => $pixel_id,
                    'id' => $copLog->id,
                ];
            } else {
                $logs[] = [
                    'pixel_id' => $pixel_id,
                    'id' => $log->id,
                ];
            }
        }
        return $logs;
    }

    /**
     * @param Event $event
     * @param array $logs
     * @return void
     * @desc 并发发送批量像素事件
     */
    public function sendBatchAsyncEventRequest(Event $event,array $logs)
    {
        Api::init(null, null, self::FB_ACCESS_TOKEN);
        $batchSize = 10;
        $chunks = array_chunk($logs, $batchSize);
        foreach ($chunks as $chunkIndex => $chunk) {
            $promises = [];
            foreach ($chunk as $item) {
                $pixelId = $item['pixel_id'];
                $logId = $item['id'];
                $request = (new EventRequestAsync($pixelId))
                    ->setEvents([$event]);
                $promises[$logId] = $request->execute();
            }
            // 批量执行并等待当前批次完成
            $results = Utils::settle($promises)->wait();
            $requestData = $event->normalize();
            $updateData = [];
            foreach ($results as $id => $result) {
                $params['request'] = $requestData ;
                $isTrack = 0;
                $trace_id = '';
                if ($result['state'] === 'fulfilled') {
                    $response = Arr::get($result, 'value');
                    $content = $response->getBody()->getContents();
                    // 2. 通常是 JSON，建议转数组
                    $body = $params['result'] = json_decode($content, true);
                    $isTrack = 1;
                    $trace_id = Arr::get($body,'fbtrace_id');
                } else {
                    $isTrack = 0;
                    $error = Arr::get($result,'reason');
                    if(method_exists($error,'getMessage')){
                        $params['error']['msg'] = $error->getMessage();
                    }
                    if (method_exists($error, 'getLastResponse')) {
                        $errorResponse = $error->getLastResponse();
                        $params['error']['body'] = $errorResponse->getBody();
                    }
                    if(method_exists($error,'getHandlerContext')){
                        $params['error']['handler_context'] = $error->getHandlerContext();
                    }
                }
                echo sprintf("id: %s , trace_id: %s",$id,$trace_id).PHP_EOL;
                $updateData[] = [
                    'id' => $id,
                    //'response' => $params,
                    'is_track'=>$isTrack,
                    'trace_id'=>$trace_id,
                ];
            }
            //dump($updateData);
            //批量更新数据库
            if($updateData) BatchUpdate::update("ddhd_sp_pixel_logs",$updateData);
            // 可选：每批间暂停 0.5 秒
            usleep(200000); // 500ms
        }

    }

    /**
     * @param PixelLogs $log
     * @return bool
     * @desc 并发追踪浏览事件
     */
    public function Track_view(PixelLogs $log): bool
    {
        $logs = $this->copyPixelTrackLogByPixelIds($log);
        if (empty($logs)) return false;
        $event = $this->createViewContentEvent($log);
        $this->sendBatchAsyncEventRequest($event,$logs);
        return true;
    }

    public function Track_purchase(PixelLogs $log): bool
    {
        $logs = $this->copyPixelTrackLogByPixelIds($log);
        if (empty($logs)) return false;
        $event = $this->createPurchaseEvent($log);
        //dd($event);
        $this->sendBatchAsyncEventRequest($event,$logs);
        return true;

    }


}